import Vue from 'vue';
var DkUI = {};
DkUI.install = function(Vue,options){
  new Component("select");
  new Component("switch");
  new Component("table");
  new Component("pagination");
  new Component("message", options);
  new Component('checkBox');
  new Component('range');
  new Component('offset');
  new Component('radio');
  new Component('input');

}

class Component {
  constructor(directive,options) {
    this[directive](options);
  }

  select(){
    Vue.component("dkSelect",{
      template:'<div class="dk-select">' +
                  '<div @click="inputClick" class="dk-select-container">' +
                    '<input v-model="selectValue" readonly type="text" :placeholder="placeholder" class="dk-select-input">' +
                    '<span class="dk-select-icon" :class="isSelect ? down : up"><i class="dk-icon-down-open"></i></span>' +
                  '</div>' +
                  '<transition name="select"><div v-show="isSelect" class="dk-select-menu">' +
                    '<ul>' +
                      '<li :class="{selected : iscur==index}" @mouseover="iscur = index" @click="select(index,option)" v-for="(option,index) in options">{{option.item}}</li>' +
                    '</ul>' +
                  '</div></transition>' +
                '</div>',
      props:['options','placeholder'],
      data:function(){
        return {
          iscur:'',
          isSelect:false,
          selectValue:'',
          down:"dk-select-icon-active",
          up:""
        }
      },
      methods:{
        select:function(index,option){
          if(option){
              this.iscur = index;
              this.selectValue = option.item;
          }
          this.isSelect = false;
          this.$emit('select',option.value);
        },
        inputClick:function(e){
          this.up = "dk-select-icon-done"
          e.stopPropagation();
          this.isSelect = true;
        }
      },
      mounted:function(){
        document.addEventListener('click',() => {
          this.isSelect = false;
        },false)
      }
    })
  }

  switch(){
    Vue.component("dkSlideRadio",{
      template:'<div @click="radioClick" class="dk-slide-radio">' +
                  '<div class="dk-radio-true dk-blue" v-bind:style="trueTrans">' +
                    '<span class="dk-radio-right"></span>' +
                  '</div>' +
                  '<div class="dk-radio-false dk-default" v-bind:style="falseTrans">' +
                    '<span class="dk-radio-left"></span>' +
                  '</div>' +
                '</div>',
      methods:{
        radioClick:function(){
          if(this.isClick == true){
              this.isClick = false;
          } else {
            this.isClick = true;
          }
          if(this.isClick == false){
            this.trueTrans = {
              transform: 'translate(-60px,0px)',
              zIndex: 2
            };
            this.falseTrans = {};
          } else {
            this.falseTrans = {
              transform:'translate(60px,0px)',
              zIndex:3
            };
            this.trueTrans = {};
          }
          this.$emit('radioClick', this.isClick);
        }
      },
      data(){
        return {
          isClick:true,
          trueTrans:{},
          falseTrans:{}
        }
      }
    })
  }

  table(){
    Vue.component('dkTable',{
      template:"<div class='dk-wrap'><table class='dk-table'>" +
                  "<thead><tr>" +
                    "<th v-for='value in theads'>{{value}}</th>" +
                  "</tr></thead>" +
                  "<tbody>" +
                    "<tr :class='{default :index % 2 == 0}' v-for='(tbody, index) in tbodys'>" +
                      "<td v-for='value in tbody'>{{value}}</td>" +
                    "</tr>" +
                  "</tbody>" +
                "</table></div>",
      props:['theads','tbodys']
    })
  }

  pagination(){
    Vue.component("dkPagination",{
      template:"<div class='dk-pagination'>" +
                  "<ul>" +
                    "<li v-if='setCur != 1' class='prev' @click='setCur--, pageClick()'><a href='javascript:;'> \< </a></li>" +
                    "<li v-if='setCur == 1' class='prev'><a class='disabled'> \< </a></li>" +
                    "<li :class='{active :setCur == index}' v-for='index in indexs'>" +
                      "<a @click='btnClick(index)'>{{index}}</a>" +
                    "</li>" +
                    "<li v-if='setCur != all' class='next' @click='setCur++, pageClick()'><a href='javascript:;'> \> </a></li>" +
                    "<li v-if='setCur == all' class='next'><a class='disabled'> \> </a></li>" +
                  "</ul>" +
                "</div>",
      props:['all','cur'],
      methods:{
        pageClick:function(){
          this.count = this.setCur;
          this.$emit("pagination",this.setCur);
        },
        btnClick:function(data){
          if(this.setCur != data){
            this.setCur = data;
            this.$emit("pagination",data);
          }
        }
      },
      data(){
        return {
          setCur:''
        }
      },
      created:function(){
        this.setCur = this.cur;
      },
      computed:{
        indexs:function(){
          var left = 1;
          var right = this.all;
          var arr = [];
          if(this.all >= 5){
            if(this.setCur > 3 && this.setCur < this.all - 2){
              left = this.setCur -2;
              right = this.setCur + 2;
            } else if(this.setCur <= 3){
              left = 1;
              right = 5;
            } else{
              right = this.all;
              left = this.all - 4;
            }
          }
          while(left <= right){
            arr.push(left);
            left++;
          }
          return arr;
        }
      }
    })
  }

  message(options){
    let opt = {
      duration:2500, // 默认持续时间
      message:"操作成功",
      type:"success",
      showClose:true
    }
    if(options){
      for(let property in options){
        opt[property] = options[property]; // 使用options的配置
      }
    }

    Vue.prototype.dkMessage = function(message,type,showClose) {
      // 默认值的配置
      if(arguments.length == 0){
        message = opt.message;
        type = opt.type;
        showClose = opt.showClose;
      } else if(arguments.length == 1){
        type = opt.type;
        showClose = opt.showClose;
      } else if(arguments.length == 2){
        howClose = opt.showClose
      }

      let messageTpl = Vue.extend({
        template:'<transition appear name="dk-message-fade"><div v-if="show" class="dk-message-box clear">' +
                    '<div class="dk-message">' +
                      '<div class="dk-message-header" :class="typeClass">' +
                        '<i :class="iconClass"></i>' +
                      '</div>' +
                      '<div class="dk-message-content">' + message + '</div>' +
                      '<div v-if="showClose" class="dk-message-button">' +
                        '<i @click="cancel" class="dk-icon-cancel"></i>' +
                      '</div>' +
                    '</div>' +
                  '</div></transition>',
        methods:{
          cancel:function(){
            var dkMessage = document.querySelectorAll('.dk-message-box');
            document.body.removeChild(dkMessage[dkMessage.length-1]);
          }
        },
        data:function(){
          return {
            show:true,
            type,
            showClose,
            typeClass:"dk-blue",
            iconClass:"dk-icon-ok"
          }
        },
        mounted:function(){
          if(!type) return;
          if(type == "success"){
            this.typeClass = "dk-green";
            this.iconClass = "dk-icon-home";
          } else if(type == "error"){
            this.typeClass = "dk-red";
            this.iconClass = "dk-icon-mail";
          }
        }
      })
      let Tpl = new messageTpl();
      let tpl = Tpl.$mount().$el; // 2.创建实例，挂在到文档以后的地方

      document.body.appendChild(tpl); // 3.把创建的实例添加到body当中

      var timeout = setTimeout(function(){
        Tpl.show = false;
      }, opt.duration);

      tpl.onmouseover = function(){
        clearTimeout(timeout);
      }

      tpl.onmouseout = function(){
        timeout = setTimeout(function(){
          Tpl.show = false;
        }, opt.duration);
      }
    }
  }

  checkBox(){
    Vue.component('dkCheckbox',{
      template:'<label class="dk-checkbox-wrapper">' +
                  '<span @click="check" v-bind:class="[checked ? show : hidden]" class="dk-checkbox-icon"><i v-show="checked" class="dk-icon-ok-1"></i></span>' +
                  '<input class="dk-checkbox" :value="value" type="checkbox">' +
                  '<span class="dk-checkbox-content">{{checks.content}}</span>' +
              '</label>',
      methods:{
        check:function(){
          this.checked = !this.checked;
          if(this.value){
            this.value = "";
          } else{
            this.value = this.checks.value;
          }
          this.$emit("check", this.value);
        }
      },
      props:["checks"],
      data(){
        return {
          value:"",
          hidden:"",
          show:"dk-checkbox-checked",
          checked:false
        }
      },
      mounted:function(){
        if(this.checks.checked == true){
          this.value = this.checks.value;
          this.checked = this.checks.checked;
        }
      }
    })
  }

  range(){
    Vue.component('dkRange',{
      template:'<div class="dk-range-wrapper">' +
                  '<div @click="rangeClick" class="dk-range">' +
                    '<span @mousedown.stop="mousedown" class="dk-range-circle"></span>' +
                    '<div class="dk-ranged"></div>' +
                    '<div class="dk-range-tip">' +
                      '{{value}}' +
                      '<span></span>' +
                    '</div>' +
                  '</div>' +
                  '<div v-if="show" class="dk-range-input">' +
                    '<input @input="inputValue" v-model="value" type="number">' +
                  '</div>' +
                '</div>',
      props:['rangeNumber','showInput'],
      data(){
        return {
          value:0,
          show:false
        }
      },
      methods:{
        mousedown:function(){
          document.addEventListener("mousemove", this.slide, false);
          document.addEventListener("mouseup",() => {
            document.removeEventListener("mousemove", this.slide, false);
          },false);
        },
        slide:function(e){
          e.stopPropagation();
          var range = this.$el.children[0].children[0];
          var ranged = this.$el.children[0].children[1];
          var tip = this.$el.children[0].children[2];
          var rangeWrapper = this.$el;
          var left = e.pageX - this.dkoffset(rangeWrapper).left - 10;
          if(left >= 380){
            left = 380;
          } else if(left <= 0){
            left = 0;
          }
          this.value = Math.floor( (left / 380) * 100 );
          range.style.left = left + 'px';
          ranged.style.width = left + 5 + 'px';
          tip.style.left = left - 5 + 'px';
        },
        rangeClick:function(e){
          this.slide(e);
        },
        numberFun:function(){
          var value = Number(this.value);
          if(value >= 0 && value <= 380){
            this.data = value;
            var range = this.$el.children[0].children[0];
            var ranged = this.$el.children[0].children[1];
            var tip = this.$el.children[0].children[2];
            range.style.left = value * 3.8 + 'px';
            ranged.style.width = value * 3.8 + 5 + 'px';
            tip.style.left = value * 3.8 - 5 + 'px';
          }
        },
        inputValue:function(){
          this.numberFun();
        }
      },
      mounted:function(){
        if(this.rangeNumber){
          this.value = this.rangeNumber;
        }
        if(this.showInput){
          this.show = this.showInput
        }
        this.numberFun();
      }
    })
  }

  offset(){
    Vue.prototype.dkoffset = function(curEle){
      var totalLeft = null;
      var totalTop = null;
      var par = curEle.offsetParent;
      //首先把自己本身的相加
      totalLeft += curEle.offsetLeft;
      totalTop += curEle.offsetTop;
      //现在开始一级一级往上查找，只要没有遇到body，我们就把父级参照物的边框和偏移相加
      while (par){
          if (navigator.userAgent.indexOf("MSIE 8.0") === -1){
              //不是IE8我们才进行累加父级参照物的边框
              totalTop += par.clientTop;
              totalLeft += par.clientLeft;
          }
          //把父级参照物的偏移相加
          totalTop += par.offsetTop;
          totalLeft += par.offsetLeft;
          par = par.offsetParent;
      }
      return {left: totalLeft,top: totalTop};
      //返回一个数组，方便我们使用哦。
    }
  }

  radio(){
    Vue.component('dkRadio',{
      template:'<div class="dk-radio-group">'+
                  '<label v-for="(option, ind) in radios" class="dk-radio-wrapper">' +
                    '<span @click="radio(option, ind)" :class="[index == ind ? show : hidden]" class="dk-radio-icon">' +
                      '<i class="dk-circle"></i>' +
                    '</span>' +
                    '<input :value="value" class="dk-radio" type="radio">' +
                    '<span class="dk-radio-content">{{option.content}}</span>' +
                '</label>' +
              '</div>',
      methods:{
        radio:function(option, ind){
          this.index = ind;
          this.value = option.value;
          this.$emit("radio", this.value);
        }
      },
      props:["radios","checkIndex"],
      data(){
        return {
          show:"dk-radio-checked",
          hidden:"",
          value:"",
          index:-1
        }
      },
      mounted:function(){
        if(this.checkIndex != -1){
          this.index = this.checkIndex;
          this.value = this.radios[this.checkIndex].value;
        }
      }
    })
  }

  input(){
    Vue.component('dkInput',{
      template:'<input class="dk-input" @blur="blur" type="text"' +
               'autocomplete="off" :placeholder="placeholder" v-model="value">',
      methods:{
        blur:function(){
          this.$emit('blur', this.value)
        }
      },
      props:['placeholder'],
      data(){
        return {
          value:''
        }
      }
    })
  }
}
// 支持 CommonJS
if (typeof exports == "object") {
  module.exports = DkUI;
// 支持 AMD
} else if (typeof define == "function" && define.amd) {
  define([], function(){ return DkUI })
// Vue 是全局变量时，自动调用 Vue.use()
} else if (window.Vue) {
  window.ele = DkUI
  Vue.use(DkUI)
}
